package xyz.lne.researchgroupmanage.util;

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

/**
 * Designed By Lne.
 * 2021/2/6 22:18
 */
public class DateUtil {
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String[] DATE_PATTERNS = {"yyyy-MM-dd", "yyyy/MM/dd", "yyyy.MM.dd"};
    public static final LocalTime DEFAULT_LOCAL_TIME = LocalTime.of(0,0,0);

    public static LocalDateTime convertDateTimeFromString(String dateTimeString) throws Exception {
//       先尝试带时间的转换，无法带时间转换则改为日期转换
        LocalDateTime localDateTime = null;
        try {
            localDateTime = LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
        }catch (DateTimeParseException e){
            localDateTime = convertDateTimeFromDateString(dateTimeString);
        }
        return localDateTime;
    }

    public static LocalDateTime convertDateTimeFromDateString(String dateString) throws Exception {
//        此处转换各种格式的日期,针对只输入日期的情况
        try {
            Date date = DateUtils.parseDate(dateString, DATE_PATTERNS);
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            return LocalDateTime.of(localDate, DEFAULT_LOCAL_TIME);
        } catch (ParseException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static Date convertDateFromDateString(String dateString) throws Exception {
//        此处转换各种格式的日期,针对只输入日期的情况
        try {
            Date date = DateUtils.parseDate(dateString, DATE_PATTERNS);
            return date;
        } catch (ParseException e) {
            throw new Exception(e.getMessage());
        }
    }
}
